---
title: "El dinero trae la felicidad? Analisis en paises Europeos"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
social: menu
source_code: embed
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(ggrepel)
library(leaflet)
library(ggplot2)
library(dplyr)
library(readr)
library(rnaturalearth)
library(rnaturalearthdata)
library(RColorBrewer)
library(sf)
library(shiny)
# Leer los datos depurados
data_path <- 'C:/Users/abolsi/Reto2M8/Datos/Base de datos depurada/datos_clean.csv'
datos_dashboard <- read_csv(data_path)
# Invertir la escala de la variable 'health'
datos_dashboard <- datos_dashboard %>%
mutate(inverted_health = 6 - health)
# Crear un vector de nombres de países mapeados a los códigos de país
country_map <- c(
"AT" = "Austria",
"BE" = "Belgium",
"BG" = "Bulgaria",
"CH" = "Switzerland",
"CY" = "Cyprus",
"CZ" = "Czechia",
"DE" = "Germany",
"DK" = "Denmark",
"EE" = "Estonia",
"ES" = "Spain",
"FI" = "Finland",
"FR" = "France",
"GB" = "United Kingdom",
"HR" = "Croatia",
"HU" = "Hungary",
"IE" = "Ireland",
"IS" = "Iceland",
"IT" = "Italy",
"LT" = "Lithuania",
"LV" = "Latvia",
"ME" = "Montenegro",
"NL" = "Netherlands",
"NO" = "Norway",
"PL" = "Poland",
"PT" = "Portugal",
"RS" = "Serbia",
"SE" = "Sweden",
"SI" = "Slovenia",
"SK" = "Slovakia"
)
# Calcular la felicidad media, la salud media (invertida), el nivel de ingresos medio y la desigualdad de ingresos por país
summary_by_country <- datos_dashboard %>%
group_by(cntry) %>%
summarise(mean_happiness = mean(happy, na.rm = TRUE),
mean_income = mean(hinctnta, na.rm = TRUE),
mean_health = mean(inverted_health, na.rm = TRUE),
income_sd = sd(hinctnta, na.rm = TRUE))
# Mapear los códigos de país a nombres de países reales
summary_by_country$country_name <- country_map[summary_by_country$cntry]
# Obtener el mapa de Europa
europe_map <- rnaturalearth::ne_countries(scale = "medium", continent = "Europe", returnclass = "sf")
# Unir los datos con el mapa usando country_name y name
europe_map <- europe_map %>%
left_join(summary_by_country, by = c("name" = "country_name"))
# Calcular la desviación estándar de los ingresos, felicidad y salud por país
income_inequality <- datos_dashboard %>%
group_by(cntry) %>%
summarise(income_sd = sd(hinctnta, na.rm = TRUE),
mean_happiness = mean(happy, na.rm = TRUE),
mean_health = mean(health, na.rm = TRUE))
# Mapear los códigos de país a nombres de países reales
income_inequality$country_name <- country_map[income_inequality$cntry]
# Calcular la correlación entre desigualdad de ingresos y felicidad/salud
correlation_happiness <- cor(income_inequality$income_sd, income_inequality$mean_happiness, use = "complete.obs")
correlation_health <- cor(income_inequality$income_sd, income_inequality$mean_health, use = "complete.obs")
print(paste("Correlación entre desigualdad de ingresos y felicidad:", correlation_happiness))
print(paste("Correlación entre desigualdad de ingresos y salud:", correlation_health))
```
Análisis Geográfico
========================================================================
Column {data-width=650}
-----------------------------------------------------------------------
### Mapa Interactivo
```{r}
selectInput("variable", "Seleccione la variable a visualizar:",
choices = c("Felicidad" = "mean_happiness", "Nivel de Ingresos" = "mean_income", "Salud" = "mean_health", "Desigualdad de Ingresos" = "income_sd"))
renderLeaflet({
variable <- input$variable
pal <- if (variable == "mean_happiness") {
colorBin("Purples", domain = europe_map[[variable]], bins = 5, na.color = "transparent")
} else if (variable == "mean_income") {
colorBin("YlOrBr", domain = europe_map[[variable]], bins = 5, na.color = "transparent")
} else if (variable == "mean_health") {
colorBin("YlGn", domain = europe_map[[variable]], bins = 5, na.color = "transparent")
} else {
colorBin("Reds", domain = europe_map[[variable]], bins = 5, na.color = "transparent")
}
leaflet(data = europe_map) %>%
addTiles() %>%
setView(lng = 10, lat = 50, zoom = 5) %>%
addPolygons(fillColor = ~pal(get(variable)),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
label = ~paste(name, ": ", round(get(variable), 2))) %>%
addLegend(pal = pal, values = ~get(variable), opacity = 0.7, title = variable,
position = "bottomright")
})
leafletOutput("map")
```
Column {data-width=350}
----------------------------------------------------------------------
### Nivel de Ingresos vs. Felicidad
```{r}
income_threshold <- mean(summary_by_country$mean_income)
happiness_threshold <- mean(summary_by_country$mean_happiness)
ggplot(summary_by_country, aes(x = mean_income, y = mean_happiness, label = country_name)) +
geom_point(aes(color = ifelse(mean_income > income_threshold & mean_happiness > happiness_threshold, "resaltado", "normal"))) +
geom_text_repel(aes(color = ifelse(mean_income > income_threshold & mean_happiness > happiness_threshold, "resaltado", "normal"))) +
labs(title = "Relación entre Nivel de Ingresos y Felicidad",
x = "Nivel de Ingresos Medio",
y = "Felicidad Promedio") +
scale_color_manual(values = c("normal" = "black", "resaltado" = "purple")) +
theme_minimal() +
theme(legend.position = "none")
```
### Nivel de Ingresos vs. Salud
```{r}
health_threshold <- mean(summary_by_country$mean_health)
ggplot(summary_by_country, aes(x = mean_income, y = mean_health, label = country_name)) +
geom_point(aes(color = ifelse(mean_income > income_threshold & mean_health > health_threshold, "resaltado", "normal"))) +
geom_text_repel(aes(color = ifelse(mean_income > income_threshold & mean_health > health_threshold, "resaltado", "normal"))) +
labs(title = "Relación entre Nivel de Ingresos y Salud",
x = "Nivel de Ingresos Medio",
y = "Salud Promedio") +
scale_color_manual(values = c("normal" = "black", "resaltado" = "purple")) +
theme_minimal() +
theme(legend.position = "none")
```
Distribuciones
========================================================================
Column {data-width=250}
----------------------------------------------------------------------
### Distribución de Felicidad por País
```{r}
num_levels <- length(unique(datos_dashboard$happy))
color_palette <- colorRampPalette(brewer.pal(9, "Purples"))(num_levels)
ggplot(datos_dashboard, aes(x = factor(cntry), fill = factor(happy))) +
geom_bar(position = "fill") +
ggtitle("Distribución de Felicidad por País") +
xlab("País") +
ylab("Proporción") +
labs(fill = "Felicidad") +
scale_fill_manual(values = color_palette) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
```
Column {data-width=250}
----------------------------------------------------------------------
### Distribución de Edades
```{r}
ggplot(datos_dashboard, aes(x = agea)) + geom_histogram() + ggtitle("Distribución de Edad")
```
### Distribución de Ingresos Familiares
```{r}
ggplot(datos_dashboard, aes(x = hinctnta)) + geom_histogram() + ggtitle("Distribución de Ingresos Familiares")
```
### Distribución de Felicidad
```{r}
ggplot(datos_dashboard, aes(x = happy)) + geom_histogram() + ggtitle("Distribución de Felicidad")
```
Column {data-width=350}
----------------------------------------------------------------------
### Distribución de Niveles Educativos
```{r}
ggplot(datos_dashboard, aes(x = eisced)) + geom_histogram() + ggtitle("Distribución de Niveles Educativos")
```
### Distribución de Encuestrados por Pais
```{r}
ggplot(datos_dashboard, aes(x = cntry)) +
geom_bar(stat = "count") +
ggtitle("Distribución de Encuestrados por País") +
xlab("País") +
ylab("Número de Encuestrados") +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
```